package com.file.service.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.file.service.FileService;
import com.file.service.StaticData;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class FileServiceImpl implements FileService {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public List getAllChildrenFileName(String path, String orderby,boolean desc) {
        File file = new File(path);
        File[] files = file.listFiles();
        List<Map<String, String>> list = new ArrayList<>();
        for (File f : files) {
            Map<String, String> map = new HashMap<>();
            String absolutePath = f.getAbsolutePath();
            if (StringUtils.isNotEmpty(absolutePath) && absolutePath.contains(".")) {
                absolutePath = absolutePath.replaceAll("C:|c:", StaticData.SHOW);
                long length = f.length();
                map.put("length", String.format("%.4f", length / 1024.0 / 1024.0) + "mb");
            } else {
                map.put("length", "");
            }
            map.put("name", f.getName());
            map.put("url", absolutePath);
            map.put("time", sdf.format(new Date(f.lastModified())));
            list.add(map);
        }
        Collections.sort(list, (o1, o2) -> {
            if (StringUtils.isEmpty(orderby)) {
                String s2 = o2.get("length");
                String s1 = o1.get("length");
                if (StringUtils.isNotEmpty(s2) && StringUtils.isNotEmpty(s1)) {
                    return s2.compareTo(s1);
                }
                if (StringUtils.isEmpty(s2) && StringUtils.isEmpty(s1)) {
                    return o2.get("time").compareTo(o1.get("time"));
                }
                if (StringUtils.isNotEmpty(s2) && StringUtils.isEmpty(s1)) {
                    return 1;
                }
                if (StringUtils.isEmpty(s2) && StringUtils.isNotEmpty(s1)) {
                    return -1;
                }
                return 0;
            } else {
                if(desc){
                    return o2.get(orderby).compareTo(o1.get(orderby));
                }else{
                    return o1.get(orderby).compareTo(o2.get(orderby));
                }
            }
        });
        return list;
    }
}
